package cn.tedu.pet.product.service.impl;


import cn.tedu.pet.commons.ex.ServiceException;
import cn.tedu.pet.commons.pojo.vo.PageData;
import cn.tedu.pet.product.mapper.ClientMapper;
import cn.tedu.pet.product.mapper.PetMapper;
import cn.tedu.pet.product.pojo.entity.Client;
import cn.tedu.pet.product.pojo.param.ClientAddNewParam;
import cn.tedu.pet.product.pojo.param.ClientUpdateInfoParam;
import cn.tedu.pet.product.pojo.vo.ClientIndexVO;
import cn.tedu.pet.product.pojo.vo.ClientListItemVO;
import cn.tedu.pet.product.pojo.vo.ClientStandardVO;
import cn.tedu.pet.product.pojo.vo.PetStandardVO;
import cn.tedu.pet.product.service.IClientService;
import cn.tedu.pet.commons.util.PageInfoToPageDataConverter;
import cn.tedu.pet.commons.web.ServiceCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ClientServiceImpl implements IClientService {
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private PetMapper petMapper;

    @Override
    public PetStandardVO getStandardByName(String name) {
        PetStandardVO queryResult=petMapper.getStandardByName(name);
        if (queryResult==null){
            String message="查询宠物详情失败,宠物数据不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return queryResult;
    }

    @Override
    public void addNew(ClientAddNewParam clientAddNewParam) {
        log.debug("开始处理【添加客户】的业务，参数：{}",clientAddNewParam);
        QueryWrapper<Client> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", clientAddNewParam.getPhone());
        int phone = clientMapper.selectCount(queryWrapper);
        if (phone > 0) {
            String message = "添加客户失败，电话号码已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        QueryWrapper<Client> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("email", clientAddNewParam.getEmail());
        int email = clientMapper.selectCount(queryWrapper2);
        if (email > 0) {
            String message = "添加客户失败，电子邮箱已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Client client = new Client();
        BeanUtils.copyProperties(clientAddNewParam,client);
        client.setGmtCreate(LocalDateTime.now());
        client.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的客户数据写入到数据库，数据：{}", client);
        int rows = clientMapper.insert(client);
        if (rows != 1) {
            String message = "添加客户失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的客户数据写入到数据库，完成！");
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【删除客户】的业务，参数：{}",id);
        int rows = clientMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除客户失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将客户数据从数据库删除，完成！");
    }

    @Override
    public void updateById(Long id, ClientUpdateInfoParam clientUpdateInfoParam) {
        log.debug("开始处理【修改客户】的业务，id:{}，参数：{}",id,clientUpdateInfoParam);
        QueryWrapper<Client> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        int countById=clientMapper.selectCount(queryWrapper);
        log.debug("根据客户ID统计匹配的客户数量，结果：{}", countById);
        if (countById==0){
            String message="修改客户失败，客户数据不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        //执行修改
        Client client = new Client();
        BeanUtils.copyProperties(clientUpdateInfoParam,client);
        client.setGmtCreate(LocalDateTime.now());
        client.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的客户数据写入到数据库，数据：{}", client);
        client.setId(id);
        int rows = clientMapper.updateById(client);
        if (rows != 1) {
            String message = "修改客户失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的客户数据写入到数据库，完成！");
    }

    @Override
    public void setVip(Long id) {
        log.debug("开始处理【启用vip】的业务，参数：{}", id);
        updateVipById(id, 1);
    }

    @Override
    public void setDisable(Long id) {
        log.debug("开始处理【禁用vip】的业务，参数：{}", id);
        updateVipById(id, 0);
    }

    private void updateVipById(Long id,Integer vip){
        // 调用Mapper对象的getStandardById()方法执行查询
        ClientStandardVO clientStandardVO = clientMapper.getStandardById(id);
        // 判断查询结果是否为null，如果是，则抛出异常
        if (clientStandardVO == null){
            String message = ENABLE_TEXT[vip] + "vip失败，vip数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断查询结果中的vip与参数vip是否相同，如果是，则抛出异常（当前状态与目标状态相同，没必要执行更新）
        if (clientStandardVO.getVip().equals(vip) ) {
            String message = ENABLE_TEXT[vip] + "vip失败，此vip已经处于" + ENABLE_TEXT[vip] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //创建Category对象
        Client updateCategory = new Client();
        updateCategory.setId(id);
        updateCategory.setVip(vip);
        int rows = clientMapper.updateById(updateCategory);
        if (rows != 1) {
            String message = ENABLE_TEXT[vip] + "vip失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public List<ClientIndexVO> search(String wd) {
        List<ClientIndexVO> client = clientMapper.selectByWd(wd);
        if (client.size() == 0){
            String message = "查询客户详情失败，客户数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return client;
    }

    @Override
    public ClientStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询客户详情】的业务，参数：{}", id);
        ClientStandardVO queryResult = clientMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "查询客户详情失败，客户数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public PageData<ClientListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<ClientListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询客户列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<ClientListItemVO> list = clientMapper.list();
        PageInfo<ClientListItemVO> pageInfo = new PageInfo<>(list);
        PageData<ClientListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完毕，即将返回：{}", pageData);
        return pageData;
    }
}
